package com.wangzhen.codebase.apidemo;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

    private final Semaphore semaphore = new Semaphore(1);

    private int count = 0;

    public void addCount() {
        try {
            semaphore.acquire();
            count ++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SemaphoreDemo demo = new SemaphoreDemo();
        Thread t1 = new Thread(()-> {
            for (int i = 0; i < 10000000; i++) {
                demo.addCount();
            }
        });

        Thread t2 = new Thread(()-> {
            for (int i = 0; i < 10000000; i++) {
                demo.addCount();
            }
        });

        t1.start();t2.start();
        t1.join();t2.join();

        System.out.println(demo.count);
    }
}
